package com.ruoyi.web.controller.award.research;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.award.research.ResearchAwardInfo;
import com.ruoyi.system.domain.award.research.ResearchAwardTeacher;
import com.ruoyi.system.domain.award.research.ResearchAwardVo;
import com.ruoyi.system.service.award.research.IResearchAwardInfoService;
import com.ruoyi.system.service.award.research.IResearchAwardTeacherService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 科研获奖信息Controller
 * 
 * @author ruoyi
 * @date 2025-07-27
 */
@RestController
@RequestMapping("/award/research")
public class ResearchAwardInfoController extends BaseController
{
    @Autowired
    private IResearchAwardInfoService researchAwardInfoService;
    @Autowired
    private IResearchAwardTeacherService researchAwardTeacherService;

    /**
     * 查询科研获奖信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ResearchAwardInfo researchAwardInfo)
    {
        startPage();
        List<ResearchAwardInfo> list = researchAwardInfoService.selectResearchAwardInfoList(researchAwardInfo);
        return getDataTable(list);
    }

    /**
     * 导出科研获奖信息列表
     */
    @Log(title = "科研获奖信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ResearchAwardInfo researchAwardInfo,
                       @RequestParam(required = false) String exportFields)
    {
        List<ResearchAwardInfo> list = researchAwardInfoService.selectResearchAwardInfoList(researchAwardInfo);
        List<ResearchAwardVo> voList = new ArrayList<>();
        for(ResearchAwardInfo info : list){
            // 处理teachers列表中的rank和username
            if (info.getTeachers() != null && !info.getTeachers().isEmpty()) {
                // 这里假设取列表中第一个teacher的信息，根据实际业务调整
                for(ResearchAwardTeacher teacher : info.getTeachers()){
                    ResearchAwardVo vo = new ResearchAwardVo();
                    // 基本属性映射
                    vo.setAwardName(info.getAwardName());
                    vo.setAchievementName(info.getAchievementName());
                    vo.setAwardLevel(info.getAwardLevel());
                    vo.setOrganization(info.getOrganization());
                    vo.setOrganizationType(info.getOrganizationType());
                    vo.setAwardType(info.getAwardType());
                    vo.setTotalOrganization(info.getTotalOrganization());
                    vo.setOwnOrganizationOrder(info.getOwnOrganizationOrder());
                    vo.setAwardDate(info.getAwardDate());
                    vo.setRank(teacher.getRank());
                    vo.setUserName(teacher.getUserName());
                    voList.add(vo);
                }
            }
        }
        ExcelUtil<ResearchAwardVo> util = new ExcelUtil<ResearchAwardVo>(ResearchAwardVo.class);
        // 如果传递了导出字段，则进行处理
        if (StringUtils.isNotBlank(exportFields)) {
            // 将逗号分隔的字段转为数组，调用showColumn指定显示字段
            String[] fields = exportFields.split(",");
            util.showColumn(fields); // 关键：使用ExcelUtil已有的showColumn方法
        }

        util.exportExcel(response, voList, "科研获奖信息数据");
    }

    /**
     * 获取科研获奖信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(researchAwardInfoService.selectResearchAwardInfoById(id));
    }

    /**
     * 新增科研获奖信息
     */
    @Log(title = "科研获奖信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ResearchAwardInfo researchAwardInfo)
    {
        ResearchAwardTeacher teacher = new ResearchAwardTeacher();
        if(researchAwardInfo.getId()!=null){
            teacher.setResearchId(researchAwardInfo.getId());
        }else {
            teacher.setResearchId(-1L);
        }
        List<ResearchAwardTeacher>  teachers =  researchAwardTeacherService.selectResearchAwardTeacherList(teacher);
        // 获取当前要添加记录的userId
        Long currentUserId = researchAwardInfo.getUserId();
        if(teachers != null && !teachers.isEmpty()){
            // 遍历教师列表，检查是否有相同的userId
            for (ResearchAwardTeacher t : teachers) {
                if (t.getUserId() != null && t.getUserId().equals(String.valueOf(currentUserId) )) {
                    return error("此奖项您已经参与并有名次记录，请勿重复添加");
                }
            }
        }

        return toAjax(researchAwardInfoService.insertResearchAwardInfo(researchAwardInfo));
    }

    /**
     * 修改科研获奖信息
     */
    @Log(title = "科研获奖信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ResearchAwardInfo researchAwardInfo)
    {
        return toAjax(researchAwardInfoService.updateResearchAwardInfo(researchAwardInfo));
    }

    /**
     * 删除科研获奖信息
     */
    @Log(title = "科研获奖信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(researchAwardInfoService.deleteResearchAwardInfoByIds(ids));
    }
    /**
     * 根据关键字查询科研获奖信息
     */
    @GetMapping("/getAwardInfoByKeyword")
    public AjaxResult getAwardInfoByKeyword(  String data)
    {
        ResearchAwardInfo ra = researchAwardInfoService.getAwardInfoByKeyword(data);
        return success(ra);
    }
}
